package com.miracle.schedule.web.service;

import com.miracle.schedule.dynamicSchedule.DynamicScheduleConfigurer;
import com.miracle.schedule.web.task.TestTriggerTask2;
import com.miracle.schedule.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description 维护定时任务API
 * @Author miracle
 * @Date 2021/11/2 18:01
 * @Version 1.0
 */
@Service
public class ScheduleService {
    private static final Logger log = LoggerFactory.getLogger(ScheduleService.class);
    @Resource
    DynamicScheduleConfigurer dynamicScheduleConfigurer;


    /**
     * @Description todo 目前是加载项目内任务对象，以后可以从外部加载任务类
     * @Author  miracle
     * @Date   2021/11/3 10:09
     * @Param
     * @Return
     * @Exception
     *
     */
    public String addSchedule(String taskId, String taskBean, String cron) throws InterruptedException {
        // 等待任务调度初始化完成
        while (!dynamicScheduleConfigurer.inited())
        {
            log.debug("dynamicScheduleConfigurer init");
            Thread.sleep(100);
        }
        Runnable bean = (TestTriggerTask2) SpringUtils.getApplicationContext().getBean(taskBean);


        log.debug("已初始化，添加任务" + taskId);

        dynamicScheduleConfigurer.addTriggerTask(taskId,new TriggerTask(
                bean,new CronTrigger(cron)
        ));
        return " add success";
    }

    /**
     *
     * @param taskId
     * @param taskBean
     * @param cron
     * @return
     * @throws InterruptedException
     */
    public String editSchedule(String taskId, String taskBean, String cron) throws InterruptedException {

        Runnable bean = SpringUtils.getBean(taskBean);
        log.debug("编辑任务:" + taskId + " bean:" + bean);

        dynamicScheduleConfigurer.resetTriggerTask(taskId,new TriggerTask(
                bean,new CronTrigger(cron)
        ));
        return "edit success";
    }

    public String cancleSchedule(String taskId) throws InterruptedException {

        log.debug("取消任务" + taskId);

        dynamicScheduleConfigurer.cancelTriggerTask(taskId);
        return "edit success";
    }
}
